package com.bincloud.vue.admin.common.util;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: Rsa 工具类
 * @Author: bincloud, mvpzhou
 * @Date: Create By bincloud, mvpzhou on 2022/2/21
 */
@SuppressWarnings("unused")
public class RsaUtils {
    private RsaUtils() {}

    private static final String KEY_ALGORITHM = "RSA";
    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * 获取私钥
     * @param keyMap 密钥对
     * @return 返回私钥
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encryptBase64(key.getEncoded());
    }

    /**
     * 获取公钥
     * @param keyMap 密钥对
     * @return 返回公钥
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }

    /**
     * 将 byte[] 转换为 string
     * @param key 字节数组 公钥/私钥
     * @return 公钥/私钥 字符串
     */
    private static String encryptBase64(byte[] key) {
        return Base64.getEncoder().encodeToString(key);
    }

    /**
     * 将 String 转换为 byte[]
     * @param key 公钥/私钥 字符串
     * @return 字节数组 公钥/私钥
     */
    public static byte[] decryptBase64(String key) {
        return Base64.getDecoder().decode(key);
    }

    /**
     * 获取 公钥 私钥 对
     *
     * @return 公钥 私钥 对
     * @throws NoSuchAlgorithmException 异常
     */
    public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
        KeyPair keyPair = generateKeyPair();
        // 公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        // 私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * 生成密钥对
     * @return 密钥对
     * @throws NoSuchAlgorithmException 异常
     */
    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(2048);
        return keyPairGen.generateKeyPair();
    }
}
